package fudan.se.project.service.infrastructure.func.account.user;


import fudan.se.project.domain.conference.Topic;
import fudan.se.project.domain.conference.role.PcMember;
import fudan.se.project.domain.message.Invitation;
import fudan.se.project.domain.message.Invitation.State;
import fudan.se.project.service.infrastructure.entity.conference.TopicService;
import fudan.se.project.service.infrastructure.entity.conference.role.PcMemberService;
import fudan.se.project.service.infrastructure.entity.message.InvitationService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;

import static fudan.se.project.domain.conference.Conference.ConferenceStage.REVIEW_START;

@Service
public class InvitationAcceptService {

    private InvitationService invitationService;
    private TopicService topicService;
    private PcMemberService pcMemberService;

    public InvitationAcceptService(InvitationService invitationService,
                                   TopicService topicService,
                                   PcMemberService pcMemberService) {
        this.invitationService = invitationService;
        this.topicService = topicService;
        this.pcMemberService = pcMemberService;
    }

    @PreAuthorize("hasAuthority('USER') and " +
            "(not hasPermission(null,'conference:pcmember:'+#invitation.conference.id))")
    public boolean process(Invitation invitation, Collection<Long> topicIds) {

        if (invitation.getConference().getStage().ordinal() >= REVIEW_START.ordinal()) {
            return false;
        }

        boolean flag = true;
        HashSet<Topic> topics = new HashSet<>();
        for (Long id : topicIds) {
            Topic topic;
            if ((topic = topicService.findById(id)) == null) {
                flag = false;
                break;
            } else {
                topics.add(topic);
            }
        }
        if (!flag) {
            return false;
        } else {
            PcMember pcMember = new PcMember(invitation.getReceiver(), invitation.getConference());
            pcMember.addTopics(topics);
            pcMemberService.save(pcMember);
            invitation.setState(State.ACCEPTED);
            invitationService.save(invitation);
            return true;
        }
    }

}
